package com.yys.apm;

import com.yys.apm.boot.ApmAgentManager;
import com.yys.apm.logger.ILogger;
import com.yys.apm.logger.LoggerManager;

import java.io.InputStream;
import java.lang.instrument.Instrumentation;
import java.util.Properties;

/**
 * 代理入口
 * @author Yingsheng Ye
 * @date 2021-03-19 17:01
 */
public class ApmAgentBootStrap {

    private static final ILogger logger = LoggerManager.getLogger(ApmAgentBootStrap.class);

    private static Properties properties = null;

    private final static String DEFAULT_CONFIG = "first-apm.properties";

    public static void premain(String arg, Instrumentation instrumentation) {
        loadAndInitializeAgent(arg, instrumentation);
    }

    private static void loadAndInitializeAgent(String arg, Instrumentation instrumentation) {
        long startTime = System.currentTimeMillis();
        initConfig(arg);
        ApmAgentManager.getInstance().boot(instrumentation, properties);
        printBanner((System.currentTimeMillis() - startTime));
        Runtime.getRuntime().addShutdownHook(new Thread(ApmAgentManager.getInstance()::shutdown, "first agent shutdown thread"));
    }

    private static void initConfig(String fileName) {
        try {
            properties = new Properties();
            InputStream inputStream = ApmAgentBootStrap.class.getClassLoader()
                    .getResourceAsStream(null == fileName || "".equals(fileName) ? DEFAULT_CONFIG : fileName);
            properties.load(inputStream);
        } catch (Exception e) {
            logger.error(e,"读取配置文件异常{}" + e.getMessage());
        }
    }

    private static void printBanner(long cost) {
        String banner = "\n" +
                "*****************************\n" +
                "*                           *\n" +
                "*        &探针启动&          *\n" +
                "*                           *\n" +
                "*****************************\n" +
                ":: FIRST-APM :: (耗时%s毫秒)    \n";
        logger.info(String.format(banner, cost));
    }

}
